import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { routerRedux } from 'dva/router';
import { fakeAccountLogin, getFakeCaptcha, fakeAccountLogout } from './service';
import { getPageQuery, setAuthority } from './utils/utils';
import { notification } from 'antd';
const R = require('ramda');

export interface StateType {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    getCaptcha: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'userLogin',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload,callback }, { call, put }) {
      const response = yield call(fakeAccountLogin, { ...R.omit(['onSuccess', 'onFail'])(payload) });
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.resultCode === 'ok') {
        if(callback){callback(response)}
        if (response.content.needVerifyCode === true) {
          notification.error({
            message: `错误码：${response.resultCode}:`,
            description: '验证码不正确',
          });
        } else {
          sessionStorage.setItem('ACJSESSIONID', response.content.sessionId);
          sessionStorage.setItem('userName', response.content.userName);
          sessionStorage.setItem('lessee', response.content.lessee);

          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          let { redirect } = params as { redirect: string };
          if (redirect) {
            const redirectUrlParams = new URL(redirect);
            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);
              if (redirect.match(/^\/.*#/)) {
                redirect = redirect.substr(redirect.indexOf('#') + 1);
              }
            } else {
              window.location.href = redirect;
              return;
            }
          }

          if (payload.onSuccess) payload.onSuccess();

          yield put(routerRedux.replace(redirect || '/'));
        }
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    *logout({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogout, { ...R.omit(['onSuccess', 'onFail'])(payload) });
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });

      if (response.resultCode === 'ok') {
        if (response.content.needVerifyCode === true) {
          notification.error({
            message: `错误码：${response.resultCode}:`,
            description: '验证码不正确',
          });
        } else {
          sessionStorage.clear();

          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          let { redirect } = params as { redirect: string };
          if (redirect) {
            const redirectUrlParams = new URL(redirect);
            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);
              if (redirect.match(/^\/.*#/)) {
                redirect = redirect.substr(redirect.indexOf('#') + 1);
              }
            } else {
              window.location.href = redirect;
              return;
            }
          }
          yield put(routerRedux.replace(redirect || '/'));
        }
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },


};

export default Model;
